package slxy.jiangtao.dts.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import slxy.jiangtao.dts.core.common.bean.Constants;
import slxy.jiangtao.dts.entity.sys.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created by Jiang Tao on 2017/4/5.
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {
    private List<String> excludedUrls;

    public void setExcludeUrls(List<String> excludeUrls) {
        this.excludedUrls = excludeUrls;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestUri = request.getRequestURI();
        for (String url : excludedUrls) {
            if (requestUri.indexOf(url) != -1) {
                return true;
            }
        }
        User user = (User) request.getSession().getAttribute(Constants.USER_IN_SESSION);
        if (user == null) {
            request.getRequestDispatcher("login").forward(request, response);
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
